package com.hainingtong.core.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;

@Slf4j
/**
 * jwt安全问题 https://zhuanlan.zhihu.com/p/97017467
 */
public class JwtUtil {
    /**
     * 过期时间1.5天
     */
    public static final long EXPIRE_TIME = 36* 60 * 60 * 1000;

    /**
     * 校验token是否正确
     *
     * @param token  token
     * @param secret 加密密钥
     * @return 是否正确
     */
    public static boolean verify(String token, String secret) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            log.info(jwt + ":-token is valid");
            return true;
        } catch (Exception e) {
            log.info("The token is invalid{}", e.getMessage());
            return false;
        }
    }

    /**
     * 根据key获取token中包含的claim信息，也就是sign的时候传入的map中的信息
     * @param key
     * @return
     */
    public static String getClaim(String token, String key) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(key).asString();
        } catch (JWTDecodeException e) {
            log.error("error：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 签名生成token
     * @param data 要携带的内容
     * @param secret 加密密钥
     * @return 返回token
     */
    public static String sign(Map<String, String> data, String secret) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        JWTCreator.Builder builder = JWT.create();
        for (String key : data.keySet()) {
            builder.withClaim(key, data.get(key));
        }
        builder.withExpiresAt(date);

        return builder.sign(algorithm);
    }
}